<?php
namespace app\common\model;

use Exception;
use think\Model;
use think\Db;

class ShareEntrust extends Model
{
    // 表名
    protected $name = 'share_entrust';

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    protected $insert = ['status' => 1]; 

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    public function getStatusList()
    {
        return [
			'0' => '已取消', 
			'1' => '委托中', 
			'2' => '已成交',
		];
    }

    public function getModeList()
    {
        return [
			'buy'   => '买入', 
			'sell' => '卖出', 
		];
    }

    public function getIsAutoList()
    {
        return [
			'0' => '否', 
			'1' => '是'
		];
    }

    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getModeTextAttr($value, $data)
    {
        $index = $data['mode'];
        $list = $this->getModeList();
        return isset($list[$index]) ? $list[$index] : '';
    }

    public function getIsAutoTextAttr($value, $data)
    {
        $index = $data['is_auto'];
        $list = $this->getIsAutoList();
        return isset($list[$index]) ? $list[$index] : '';
    }

    /**
     * 委托撤销
     */
    public function revoke()
    {
        Db::startTrans();
        try {
            $this->status = 0;
            $this->updatetime = time();
            if(!$this->save()){
                throw new Exception('委托撤销失败');
            }
            //退回余额
            $earnestMoney = $this->total_earnest;
            $userInfo = User::get($this->user_id);
            updateMoney($userInfo,$earnestMoney,'委托未成,退保证金');

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error = $e->getMessage();
            return false;
        }
        return true;
    }

}
